﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;

namespace Service.Controllers
{
    public class AuthenticationController : Controller
    {
        /// <summary>
        /// 打开的登录页面
        /// </summary>
        /// <param name="clientId">应用id,预留，看情况使用</param>
        /// <param name="callbackUrl">回调url,用户处理token地址</param>
        /// <param name="jumpUrl">跳转登陆前的地址</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Login(string clientId, string callbackUrl, string jumpUrl)
        {
            ViewBag.clientId = clientId;
            ViewBag.callbackUrl = callbackUrl;
            ViewBag.jumpUrl = jumpUrl;
            return View();
        }

        /// <summary>
        /// 本系统的登录校验
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="pwd">密码</param>
        /// <param name="clientId">应用id,来自用户</param>
        /// <param name="callbackUrl">用户的回调地址</param>
        /// <param name="jumpUrl">用户的跳转地址</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(string userName, string pwd, string clientId, string callbackUrl, string jumpUrl)
        {
            if (userName.Equals("root") && pwd.Equals("admin"))
            {
                //拟定一个 token 保存到缓存(此处随意拟定一个，实际情况应该考虑各项因素)
                var token = string.Format("{0}-{1}-{2}", clientId, userName, DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                Cache cache = new Cache();
                if(cache.Get(token)!=null)
                {
                    cache.Remove(token);
                }
                //实际情况应设置超时时间
                cache.Insert(token, new { userName = "用户名", gander = "男" });


                ///这部分跳转的也可以通过前台来实现，此处偷懒
                ViewBag.callbackurl = callbackUrl;
                ViewBag.jumpurl = HttpUtility.UrlEncode(jumpUrl);
                ViewBag.token = token;
                return View("LoginCallback");
            }
            return Json(new { code = 0, msg = "用户信息验证失败!" });
        }

        /// <summary>
        /// 校验token并返回授权信息
        /// </summary>
        /// <param name="token">token</param>
        /// <returns></returns>
        public ActionResult CheckAndGetUserInfo(string token)
        {
            //此处偷懒只取缓存，检验的方法根据实际情况
            Cache cache = new Cache();
            if (cache.Get(token) != null)
            {
                var info = cache.Get(token);
                cache.Remove(token);

                return Json(new { code = 1, msg = "验证通过",data= info },"application/json;charset=utf-8",Encoding.UTF8,JsonRequestBehavior.AllowGet); 
            }
            return Json(new { code = 0, msg = "验证失败" }, "application/json;charset=utf-8", Encoding.UTF8, JsonRequestBehavior.AllowGet);
        }
    }
}